<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<!-- eslint-disable no-unused-vars -->
<template>
  <div class="farming-management-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>种植信息管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 种植信息列表 -->
    <el-card class="content-card">
      <div slot="header" class="card-header">
        <span>种植信息列表</span>
        <el-button type="primary" size="small" @click="openAddDialog">添加种植信息</el-button>
      </div>

<!--      &lt;!&ndash; 搜索区域 &ndash;&gt;-->
<!--      <el-row :gutter="20" class="search-area">-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入产品名称" v-model="queryParams.name" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click="searchFarmingInfo"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入批次号" v-model="queryParams.batchId" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click="searchFarmingInfo"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-date-picker-->
<!--            v-model="queryParams.dateRange"-->
<!--            type="daterange"-->
<!--            range-separator="至"-->
<!--            start-placeholder="种植开始日期"-->
<!--            end-placeholder="种植结束日期"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            style="width: 100%;">-->
<!--          </el-date-picker>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-button type="primary" @click="searchFarmingInfo">搜索</el-button>-->
<!--          <el-button @click="resetQuery">重置</el-button>-->
<!--        </el-col>-->
<!--      </el-row>-->

      <!-- 表格 -->
      <el-table :data="farmingList" border stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="name" label="产品名称" width="120"></el-table-column>
        <el-table-column prop="batchId" label="批次号" width="120"></el-table-column>
        <el-table-column label="种植日期" width="120">
          <template v-slot="scope">
            {{ scope.row.plantingDate || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="采收日期" width="120">
          <template v-slot="scope">
            {{ scope.row.harvestDate || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="种植面积" width="120">
          <template v-slot="scope">
            {{ scope.row.plantingArea || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="农户信息" width="120">
          <template v-slot="scope">
            {{ scope.row.user ? scope.row.user.username : '未知用户' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template v-slot="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="info" size="mini" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 新增/编辑种植信息对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" @close="resetForm">
      <el-form :model="farmingForm" :rules="farmingRules" ref="farmingFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="farmingForm.name" placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchId">
              <el-input v-model="farmingForm.batchId" placeholder="请输入批次号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="种植日期" prop="plantingDate">
              <el-date-picker
                v-model="farmingForm.plantingDate"
                type="date"
                placeholder="选择种植日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采收日期" prop="harvestDate">
              <el-date-picker
                v-model="farmingForm.harvestDate"
                type="date"
                placeholder="选择采收日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="种植面积" prop="plantingArea">
              <el-input v-model="farmingForm.plantingArea" placeholder="请输入种植面积（亩）"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品质等级" prop="qualityLevel">
              <el-select v-model="farmingForm.qualityLevel" placeholder="请选择品质等级" style="width: 100%;">
                <el-option label="特级" value="特级"></el-option>
                <el-option label="一级" value="一级"></el-option>
                <el-option label="二级" value="二级"></el-option>
                <el-option label="三级" value="三级"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="施肥情况" prop="fertilizerUsed">
              <el-input v-model="farmingForm.fertilizerUsed" type="textarea" :rows="2" placeholder="请输入施肥情况"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用药情况" prop="pesticideUsed">
              <el-input v-model="farmingForm.pesticideUsed" type="textarea" :rows="2" placeholder="请输入用药情况"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存储方式" prop="storageMethods">
              <el-input v-model="farmingForm.storageMethods" placeholder="请输入存储方式"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属农户" prop="userId">
              <el-select v-model="farmingForm.userId" placeholder="请选择所属农户" style="width: 100%;" filterable>
                <el-option 
                  v-for="user in farmerOptions" 
                  :key="user.id" 
                  :label="user.username" 
                  :value="user.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remarks">
          <el-input v-model="farmingForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="种植信息详情" v-model="detailVisible" width="60%">
      <el-descriptions border :column="2">
        <el-descriptions-item label="产品名称">{{ detailInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="批次号">{{ detailInfo.batchId }}</el-descriptions-item>
        <el-descriptions-item label="种植日期">{{ detailInfo.plantingDate }}</el-descriptions-item>
        <el-descriptions-item label="采收日期">{{ detailInfo.harvestDate }}</el-descriptions-item>
        <el-descriptions-item label="种植面积">{{ detailInfo.plantingArea }}</el-descriptions-item>
        <el-descriptions-item label="品质等级">{{ detailInfo.qualityLevel }}</el-descriptions-item>
        <el-descriptions-item label="所属农户">{{ detailInfo.user ? detailInfo.user.username : '未知用户' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(detailInfo.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(detailInfo.updatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="施肥情况" :span="2">{{ detailInfo.fertilizerUsed || '无' }}</el-descriptions-item>
        <el-descriptions-item label="用药情况" :span="2">{{ detailInfo.pesticideUsed || '无' }}</el-descriptions-item>
        <el-descriptions-item label="存储方式" :span="2">{{ detailInfo.storageMethods || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailInfo.remarks || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入API
import { farmingAPI, userAPI } from '@/api/api';

export default {
  name: 'FarmingManagementView',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        batchId: '',
        dateRange: []
      },
      // 总记录数
      total: 0,
      // 种植信息列表
      farmingList: [],
      // 对话框显示状态
      dialogVisible: false,
      detailVisible: false,
      // 对话框标题
      dialogTitle: '新增种植信息',
      // 表单数据
      farmingForm: {
        id: null,
        name: '',
        batchId: '',
        plantingDate: '',
        harvestDate: '',
        plantingArea: '',
        fertilizerUsed: '',
        pesticideUsed: '',
        storageMethods: '',
        qualityLevel: '',
        remarks: '',
        userId: null
      },
      // 表单校验规则
      farmingRules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        plantingDate: [
          { required: true, message: '请选择种植日期', trigger: 'change' }
        ],
        userId: [
          { required: true, message: '请选择所属农户', trigger: 'change' }
        ]
      },
      // 详情数据
      detailInfo: {},
      // 农户选项
      farmerOptions: [],
      // 加载状态
      loading: false,
      submitting: false
    }
  },
  created() {
    this.getFarmingList();
    this.getFarmerOptions();
  },
  methods: {
    // 获取种植信息列表
    async getFarmingList() {
      try {
        this.loading = true;

        // 构建查询参数
        const params = {
          page: this.queryParams.pageNum - 1, // 后端分页从0开始
          size: this.queryParams.pageSize,
          sort: 'createdAt,desc',
          keyword: this.queryParams.name || this.queryParams.batchId
        };

        // 添加日期范围参数
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
          params.fromDate = this.queryParams.dateRange[0];
          params.toDate = this.queryParams.dateRange[1];
        }

        const response = await farmingAPI.getAllFarmingInfo(params);
        
        if (response && response.data) {
          this.farmingList = response.data.content || [];
          this.total = response.data.totalElements || 0;
        } else {
          this.$message.error('获取种植信息列表失败');
        }

        this.loading = false;
      } catch (error) {
        console.error('Failed to fetch farming list:', error);
        this.$message.error('获取种植信息列表失败: ' + (error.message || '服务器错误'));
        this.loading = false;
      }
    },

    // 获取农户选项
    async getFarmerOptions() {
      try {
        const response = await userAPI.getUserList({ role: 'FARMER' });
        
        if (response && response.data) {
          this.farmerOptions = response.data.list || response.data || [];
        } else {
          console.error('获取农户列表失败:', response);
        }
      } catch (error) {
        console.error('Failed to fetch farmer options:', error);
        this.$message.error('获取农户列表失败: ' + (error.message || '服务器错误'));
      }
    },

    // 搜索种植信息
    searchFarmingInfo() {
      this.queryParams.pageNum = 1;
      this.getFarmingList();
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: '',
        batchId: '',
        dateRange: []
      };
      this.getFarmingList();
    },

    // 处理每页数量变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getFarmingList();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getFarmingList();
    },

    // 打开添加对话框
    openAddDialog() {
      this.dialogTitle = '新增种植信息';
      this.resetForm();
      this.dialogVisible = true;
    },

    // 处理编辑
    async handleEdit(row) {
      this.dialogTitle = '编辑种植信息';
      this.resetForm();
      
      try {
        const response = await farmingAPI.getFarmingInfoById(row.id);
        
        if (response && response.data) {
          const farmingData = response.data;
          
          this.farmingForm = {
            id: farmingData.id,
            name: farmingData.name,
            batchId: farmingData.batchId,
            plantingDate: farmingData.plantingDate,
            harvestDate: farmingData.harvestDate,
            plantingArea: farmingData.plantingArea,
            fertilizerUsed: farmingData.fertilizerUsed,
            pesticideUsed: farmingData.pesticideUsed,
            storageMethods: farmingData.storageMethods,
            qualityLevel: farmingData.qualityLevel,
            remarks: farmingData.remarks,
            userId: farmingData.user ? farmingData.user.id : null
          };
          
          this.dialogVisible = true;
        } else {
          this.$message.error('获取种植信息详情失败');
        }
      } catch (error) {
        console.error('Failed to fetch farming details:', error);
        this.$message.error('获取种植信息详情失败: ' + (error.message || '服务器错误'));
      }
    },

    // 处理查看详情
    async handleView(row) {
      try {
        const response = await farmingAPI.getFarmingInfoById(row.id);
        
        if (response && response.data) {
          this.detailInfo = response.data;
          this.detailVisible = true;
        } else {
          this.$message.error('获取种植信息详情失败');
        }
      } catch (error) {
        console.error('Failed to fetch farming details:', error);
        this.$message.error('获取种植信息详情失败: ' + (error.message || '服务器错误'));
      }
    },

    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该种植信息记录吗？此操作不可逆', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await farmingAPI.deleteFarmingInfo(row.id);
          
          if (response && response.success) {
            this.$message.success('删除成功');
            this.getFarmingList();
          } else {
            this.$message.error('删除失败: ' + (response.message || '未知错误'));
          }
        } catch (error) {
          console.error('Failed to delete farming info:', error);
          this.$message.error('删除失败: ' + (error.message || '服务器错误'));
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.farmingFormRef) {
        this.$refs.farmingFormRef.resetFields();
      }
      
      this.farmingForm = {
        id: null,
        name: '',
        batchId: '',
        plantingDate: '',
        harvestDate: '',
        plantingArea: '',
        fertilizerUsed: '',
        pesticideUsed: '',
        storageMethods: '',
        qualityLevel: '',
        remarks: '',
        userId: null
      };
    },

    // 提交表单
    submitForm() {
      this.$refs.farmingFormRef.validate(async (valid) => {
        if (valid) {
          this.submitting = true;
          
          try {
            let response;
            
            // 构建提交数据
            const farmingData = { ...this.farmingForm };
            
            if (this.farmingForm.id) {
              // 编辑
              response = await farmingAPI.updateFarmingInfo(this.farmingForm.id, farmingData);
            } else {
              // 新增
              response = await farmingAPI.saveFarmingInfo(this.farmingForm.userId, farmingData);
            }
            
            if (response && response.success) {
              this.$message.success(this.farmingForm.id ? '更新成功' : '添加成功');
              this.dialogVisible = false;
              this.getFarmingList();
            } else {
              this.$message.error((this.farmingForm.id ? '更新' : '添加') + '失败: ' + (response.message || '未知错误'));
            }
          } catch (error) {
            console.error('Failed to save farming info:', error);
            this.$message.error((this.farmingForm.id ? '更新' : '添加') + '失败: ' + (error.message || '服务器错误'));
          } finally {
            this.submitting = false;
          }
        } else {
          this.$message.warning('请正确填写表单信息');
          return false;
        }
      });
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
  }
}
</script>

<style scoped>
.farming-management-container {
  padding: 20px;
}

.content-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 